<?php

namespace app\services;

use app\lib\exception\ParamException;
use app\model\AirplanePassenger;
use app\utils\DateTime;
use app\validate\OrderValidate;

class PassengerService
{
    /**
     * @var AirplanePassenger
     */
    private $dao;

    public function __construct()
    {
        $this->dao = new AirplanePassenger();
    }



    public function add($passengerList, $fly_day){

        $saveList = [];
        $aduList = [];
        $inftList = [];
        $chdList = [];
        foreach ($passengerList as $passengerInfo){
            validate(OrderValidate::class)
                ->scene('passenger')
                ->check($passengerInfo);

            if ($passengerInfo['is_chd'] == 1){
                if (DateTime::calculateAge($passengerInfo['birthday'], $fly_day)>=12)  throw new ParamException($passengerInfo['name'].':儿童年龄满12岁,请购买成人票;');
                $db_chd = $this->dao->where(['is_chd' => 1,'name' => $passengerInfo['name'], 'id_card' => $passengerInfo['id_card']])->find();
                if (empty($db_chd)){
                    $chdList[]= $this->dao->create($passengerInfo);
                }else{
                    $chdList[] = $db_chd;
                }
                continue;
            }


            $whereList = $passengerInfo;
            unset($whereList['inft'], $whereList['is_frequently'], $whereList['card_expiration']);
            $db_passenger = $this->dao->where($whereList)->find();
            if (!empty($passengerInfo['inft'])){


                if (DateTime::calculateAge($passengerInfo['inft']['birthday'], $fly_day)>=2)  throw new ParamException($passengerInfo['inft']['name'].':婴儿年龄满2岁,请购买儿童票;');
                $db_inft = $this->dao->where(['name' => $passengerInfo['inft']['name'], 'birthday' => $passengerInfo['inft']['birthday']])->find();
                if (empty($db_inft)){
                    $inftList[$passengerInfo['name']]= $this->dao->create([
                        'name'=>$passengerInfo['inft']['name'],
                        'birthday'=>$passengerInfo['inft']['birthday'],
                        'is_inft'=>1
                    ]);
                }else{
                    $inftList[$passengerInfo['name']] = $db_inft;
                }


            }

            if (empty($db_passenger)){
                unset($passengerInfo['inft']);
                $saveList[] = $passengerInfo;
            }else{
                $aduList[] = $db_passenger;
            }

        }


        return ['adu'=> array_merge($aduList, $this->dao->saveAll($saveList)->toArray()),'inft' => $inftList, 'chd' => $chdList];
    }


    public function getList($keyword){
        return $this->dao->where('is_frequently',1)->where('name|second_name|id_card|email','like', '%'.$keyword.'%')->order('create_time','desc')->select();
    }
}


